import {
  MAX_COL_NUM,
  MENU_CONFIGURATION,
  MENU_NAME_CONFIGURATION,
  START_NUMBER,
  DEFAULT_COORDINATE,
  MODULE_TYPE,
} from "@/utils/mockConfiguration/mockConfig";
import { cloneDeep, last } from "lodash";
import { storeToRefs } from "pinia";
import { v4 } from "uuid";
import { useTemplateEditing } from "@/store/modules/templateEditing";

const templateEditing = useTemplateEditing();
const { templateSelection, updateDimensions } = templateEditing;
const { currentSettings, templatePageIndex, fileName, templateSettings, menuButton, templatePage } = storeToRefs(templateEditing);
const { baseConfig } = currentSettings.value;
const { SET_ID_MODULE, MODULE_SELECTION, QUESTION_MODULE, LEAGUE_TABLES } = MODULE_TYPE;
export default function useEditThePage() {
  /**
   * 删除模块
   * @param {Array} data 模块数据
   * @param {String} id 要删除的id
   */
  const deleteBtn = (data = [], id = "") => {
    currentSettings.value.modules = data.filter(item => item.cssStyle.i !== id);
    moveEventEnd(); //重新排序简答题和选择题
    //默认选中基础配置
    menuButton.value = "basicConfiguration";
    templateSettings.value = baseConfig;
    templatePageIndex.value = null;
  };

  /**
   * 拖拽结束后重新排序
   */
  const moveEventEnd = () => {
    templatePage.value
      .filter(item => QUESTION_MODULE.includes(item.moduleId))
      .sort((preData, postData) => {
        const { y: preY, x: preX } = preData.cssStyle;
        const { y: postY, x: postX } = postData.cssStyle;
        return preY === postY ? preX - postX : preY - postY;
      })
      .map((list, index) => {
        const id = index + START_NUMBER;
        list.businessData.id = id;
        list.id = id;
        return list; // 返回修改后的对象
      });
  };

  /**
   * 模块添加
   * @param {Object} value 模板数据
   */
  const addModules = value => {
    const { cssStyle, moduleType } = value;
    const data = cloneDeep(value);
    const { cssStyle: dataCssStyle } = data;
    const id = v4();
    dataCssStyle.i = id;
    //当为基础模块/排行榜的时候，设置id
    SET_ID_MODULE.includes(moduleType) && (data.id = id);
    const lastModule = last(templatePage.value)?.cssStyle;
    //当首次添加的时候，直接添加数据
    if (!lastModule) {
      templatePage.value.push(data);
      return data;
    }
    const { x, y, w, h } = lastModule; //获取最后一个模块的y坐标和h高度
    const { w: newW } = cssStyle; //获取当前模块的宽
    //判断新元素的位置是否超出了最大列数的限制
    const condition = x + w + newW > MAX_COL_NUM;
    //如果超出最大列数，将元素的位置重置到最左边，否则根据当前位置和宽度进行更新
    dataCssStyle.x = condition ? DEFAULT_COORDINATE : x + w;
    //不论是否超出最大列数，都根据当前位置和高度更新元素的y坐标
    dataCssStyle.y = condition ? y + h : y;
    templatePage.value.push(data);
    return data;
  };

  /**
   * 模板复制和添加
   * @param {Object} value 模板数据
   */
  const templatesAreCopiedAndAdded = value => {
    fileName.value = "";
    const { moduleId } = value; // 解构 value 对象
    if (MODULE_SELECTION.includes(moduleId)) {
      //当为基础配置和组配置时，不添加数据去预览数据
      menuButton.value = moduleId;
      templateSettings.value = baseConfig;
      templatePageIndex.value = null;
      return;
    }
    if (LEAGUE_TABLES.includes(moduleId)) {
      //当为参与率排行版或者得分数排行榜时，默认添加简文本模块，所以需要在模块配置查找简文本模块
      const textData = cloneDeep(MENU_CONFIGURATION.find(item => item.moduleId === "text"));
      textData.businessData.content = MENU_NAME_CONFIGURATION[moduleId];
      templatesAreCopiedAndAdded(textData);
      return;
    }
    //添加模块
    const data = addModules(value);
    //重新排序简答题和选择题
    moveEventEnd();
    //在DOM更新后，确保元素滚动到可视区域
    const length = templatePage.value.length;

    nextTick(() => {
      requestAnimationFrame(() => {
        //将当前数据项对应的元素滚动到视图中
        document.getElementById("bottomItem").scrollIntoView({ behavior: "smooth" });
        updateDimensions(data.cssStyle.i);
        //默认选择新增模块
        templateSelection(data, length - START_NUMBER);
      });
    });
  };
  return {
    templatesAreCopiedAndAdded, //模块复制和添加
    moveEventEnd, //重新排序简答题和选择题
    deleteBtn, //删除模块
  };
}
